package com.framework.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.framework.app.entity.AppMember;
import com.framework.app.entity.dto.LoginDTO;
import com.framework.app.mapper.AppMemberMapper;
import com.framework.app.service.IAppMemberLoginService;
import com.framework.core.common.bo.AppMemberBO;
import com.framework.core.common.bo.LoginUser;
import com.framework.core.common.constant.Constants;
import com.framework.core.common.enums.DelFlagEnum;
import com.framework.core.common.enums.GrantTypeEnum;
import com.framework.core.common.enums.StatusEnum;
import com.framework.core.common.enums.UserPlatformEnum;
import com.framework.core.exception.CustomException;
import com.framework.core.util.AddressUtil;
import com.framework.core.util.IpUtil;
import com.framework.core.util.SecurityUtil;
import com.framework.core.util.StpAppUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * 用户实现类
 *
 * @author Kevin
 */
@Slf4j
@Service
@AllArgsConstructor
public class AppMemberLoginServiceImpl implements IAppMemberLoginService {

    private AppMemberMapper appUserMapper;

    @Override
    public String login(LoginDTO req) {
        AppMember appUser = null;
        if (StrUtil.isBlank(req.getUsername())) {
            throw new CustomException("用户名不能为空");
        }
        if (StrUtil.isBlank(req.getPassword())) {
            throw new CustomException("密码不能为空");
        }
        appUser = appUserMapper.selectOne(Wrappers.lambdaQuery(AppMember.class)
                .eq(AppMember::getAccount, req.getUsername())
                .eq(AppMember::getDelFlag, DelFlagEnum.NO.getCode()));
        if (Objects.isNull(appUser)) {
            log.info("登录用户：{}不存在", req.getUsername());
            throw new CustomException("登录用户不存在");
        }
        if (!SecurityUtil.matchesPassword(req.getPassword(), appUser.getPassword())) {
            throw new CustomException("账号或密码不正确");
        }
        if (appUser.getStatus().equals(StatusEnum.NO.getCode())) {
            log.info("登录用户：{}已被停用", req.getUsername());
            throw new CustomException("对不起，您的账号已被停用");
        }
        log.info("登录用户：{}", req.getUsername());
        AppMemberBO appMemberBO = BeanUtil.copyProperties(appUser, AppMemberBO.class);
        // 登录
        StpAppUtil.login(appUser.getId());
        LoginUser loginUser = new LoginUser();
        loginUser.setToken(StpAppUtil.getTokenValue());
        loginUser.setUserPlatform(UserPlatformEnum.APP.getCode());
        loginUser.setGrantType(req.getGrantType());
        loginUser.setAppMemberBO(appMemberBO);
        if (req.getGrantType().equals(GrantTypeEnum.USERNAME_PASSWORD.getCode())) {
            loginUser.setUsername(req.getUsername());
        }
        if (req.getGrantType().equals(GrantTypeEnum.MOBILE_CODE.getCode())) {
            loginUser.setUsername(req.getMobile());
        }
        loginUser.setLoginTime(new Date());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String ipAddress = IpUtil.getClientIp(request);
        loginUser.setIpAddress(ipAddress);
        loginUser.setLoginLocation(AddressUtil.getRealAddressByIp(ipAddress));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOs().getName());
        // 设置用户信息
        StpAppUtil.getTokenSession().set(Constants.LOGIN_USER_KEY, loginUser);
        return StpAppUtil.getTokenValue();
    }

}
